<template>
  <div class="uploadContent">
    <el-upload
      class="upload-demo"
      ref="upload"
      action="#"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :http-request="upload"
      name="photo"
      :auto-upload="false"
      :before-upload="beforeAvatarUpload">
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'UploadAvatar',
  methods: {
    submitUpload () {
      this.$refs.upload.submit()
    },
    beforeAvatarUpload(file) {
      let type = file.type;
      const flg1 = !(type === 'image/jpeg' || type === 'image/png')
      const flg2 = file.size / 1024 / 1024 > 1

      if (flg1) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式！')
      }

      if (flg2) {
        this.$message.error('上传头像图片大小不能超过 1MB！')
      }
      return !flg1 && !flg2
    },
    upload (param) {
      const formData = new FormData()
      formData.append('photo', param.file)
      this.$request({
        method: 'post',
        url: '/user/updatephoto',
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        data: formData
      }).then(result => {
        if (result.code === 200 && result.data != null) {
          this.$alert('上传头像成功！')
          let avatar = result.data
          sessionStorage.setItem('avatar', avatar)
          location.reload()
        } else if (result.code === -1) {
          this.$message.error(result.msg)
        } else {
          this.$message.error('上传头像失败！')
        }
      })
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    }
  }
}
</script>

<style scoped>
.uploadContent{
   margin-top: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

</style>
